package com.zx.chatroom.action;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.corundumstudio.socketio.SocketIOClient;
import com.zx.chatroom.listener.HallListener;
import com.zx.chatroom.listener.TalkListener;
import com.zx.chatroom.server.SocketServer;
import com.zx.chatroom.vo.Chat;
import com.zx.chatroom.vo.UserVo;
import com.zx.framework.core.env.Environment;
import com.zx.framework.core.util.FileUtil;
import com.zx.framework.core.util.SequenceUtil;
import com.zx.framework.core.util.StringUtil;
import com.zx.framework.web.action.spring.BaseController;

@Controller
@RequestMapping
public class UploadController extends BaseController {
	@Resource
	private String uploadImgPath;
	@Resource
	private String uploadFilePath;
	

	/**
	 * ueditor图片上传，在处理完毕后要将图片放置到需要的目录
	 * 
	 * @param request
	 * @return Map<String,Object>
	 * @author daichen
	 */
	@RequestMapping(value = "/imageUpload", method = { RequestMethod.POST,
			RequestMethod.GET })
	public @ResponseBody
	Map<String, Object> imageUpload(HttpServletRequest request) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			File upload = new File(uploadImgPath);
			if(!upload.exists()){
				upload.mkdirs();
			}
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

			String fileName = multiRequest.getParameter("fileName");
			String fileRemark = multiRequest.getParameter("pictitle");
			String id = SequenceUtil.getUUID();
			String suff = FileUtil.getFileExtension(fileName);
			List<MultipartFile> files = multiRequest.getMultiFileMap().get("upfile");
			if (files != null && !files.isEmpty()) {
				MultipartFile file = files.get(0);
				FileUtil.copyInputStreamToFile(file.getInputStream(),new File(upload.getAbsolutePath()+File.separator + id + suff));
			}
			HallListener hallListener = HallListener.getInstance();
			dataMap.put("original", fileName);
			dataMap.put("url", "download/"+id + suff+"/");
			dataMap.put("title", fileRemark);
			dataMap.put("state", "SUCCESS");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataMap;
	}

	/**
	 * ueditor附件上传
	 * @param request
	 * @return Map<String,Object>
	 * @author daichen
	 */
	@RequestMapping(value = "/fileUp", method = { RequestMethod.POST,RequestMethod.GET },
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public @ResponseBody String fileUp(HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			File upload = new File(uploadFilePath);
			if(!upload.exists()){
				upload.mkdirs();
			}
			
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> files = multiRequest.getFiles("uploadFiles");
			MultipartFile multipartFile = files.get(0);
			//好像不用判断 multipartFile.isEmpty();
			//获取上传文件文件名
			String fileName = multipartFile.getOriginalFilename();
			String id =SequenceUtil.getUUID();
			//获取上传文件扩展名
			String suff = FileUtil.getFileExtension(fileName);
			//保存上传文件
			FileUtil.copyInputStreamToFile(multipartFile.getInputStream(), new File(upload.getAbsolutePath()+File.separator + id + suff));
			dataMap.put("original", fileName);
		
			String keyFileName =URLEncoder.encode(fileName, "utf-8");
			
			dataMap.put("url", "download/"+keyFileName+"/"+ id+"/");
			dataMap.put("title", fileName);
			dataMap.put("fileType", suff);
			dataMap.put("state", "SUCCESS");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return gson.toJson(dataMap);
	}
	@RequestMapping(value = "/snapscreenUp/{fromId}/{toId}/{roomName}", method = { RequestMethod.POST,RequestMethod.GET },
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public void snapscreenUp(HttpServletResponse response ,HttpServletRequest request,@PathVariable("fromId") String fromId,@PathVariable("toId") String toId,
			@PathVariable("roomName") String roomName){
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			File upload = new File(uploadFilePath);
			if(!upload.exists()){
				upload.mkdirs();
			}
			
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> files = multiRequest.getFiles("imageuploadfile");
			MultipartFile multipartFile = files.get(0);
			//好像不用判断 multipartFile.isEmpty();
			//获取上传文件文件名
			String fileName = multipartFile.getOriginalFilename();
			String id =SequenceUtil.getUUID();
			//获取上传文件扩展名
			String suff = FileUtil.getFileExtension(fileName);
			//保存上传文件
			String snapscreenRealPath = Environment.WEB_REALPATH+File.separator + "snapscreenFiles"+File.separator + id + suff;
			FileUtil.copyInputStreamToFile(multipartFile.getInputStream(), new File(snapscreenRealPath));
			String snapscreenPath = Environment.CONTEXT.getContextPath()+"/" + "snapscreenFiles"+"/"+ id + suff;
			if (roomName.equals(SocketServer.HALL)) {
				HallListener hallListener = HallListener.getInstance();
				SocketIOClient fromClient = hallListener.findSocketByUserId(fromId);
				UserVo fromUser = hallListener.findOnlineUserByUserId(fromId);
				String jsonInfo = "{'imgSrc':'<img src=\""+snapscreenPath+"\"/>','fromUserName':'"+fromUser.getUsername()+"'}";
				fromClient.sendEvent("snapscreenPath", jsonInfo);
				SocketIOClient toClient = hallListener.findSocketByUserId(toId);
				toClient.sendEvent("snapscreenPath", jsonInfo);
			} else if(roomName.equals(SocketServer.TALK)){
				TalkListener talkListener = TalkListener.getInstance();
				UserVo fromUser = talkListener.findOnlineUserByUserId(fromId);
				List<UserVo> list = talkListener.getUserByGroupid(toId);
				SocketIOClient ather = null;
				for (UserVo user : list) {
					ather = talkListener.findSocketByUserId(user.getId());
					String jsonInfo = "{'imgSrc':'<img src=\""+snapscreenPath+"\"/>','fromUserName':'"+fromUser.getUsername()+"'}";
					ather.sendEvent("snapscreenPath", jsonInfo);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
